package init

import (
	"encoding/json"
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"srv/appconfig"
	"srv/global"
)

func init() {
	appconfig.Init()
	initnacos()
	initmysql()
}

type T struct {
	Myslq struct {
		User     string `json:"User"`
		Password string `json:"Password"`
		Host     string `json:"Host"`
		Port     int    `json:"Port"`
		Database string `json:"Database"`
	} `json:"myslq"`
	Redis struct {
		Addr     string `json:"Addr"`
		Password string `json:"Password"`
		DB       int    `json:"DB"`
	} `json:"redis"`
}

var ns T

func initnacos() {
	var nsa = appconfig.Config.Nacos
	//create clientConfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         nsa.NamespaceId, //we can create multiple clients with different namespaceId to support multiple namespace.When namespace is public, fill in the blank string here.
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "debug",
	}
	// At least one ServerConfig
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      nsa.IpAddr,
			ContextPath: "/nacos",
			Port:        uint64(nsa.Port),
			Scheme:      "http",
		},
	}

	// Create config client for dynamic configuration
	clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})
	// Another way of create config client for dynamic configuration (recommend)
	configClient, _ := clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfigs,
		},
	)
	content, _ := configClient.GetConfig(vo.ConfigParam{
		DataId: nsa.DataId,
		Group:  nsa.Group})
	err := json.Unmarshal([]byte(content), &ns)
	if err != nil {
		return
	}
	fmt.Println(content)
}
func initmysql() {
	var mq = ns.Myslq
	var err error
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", mq.User, mq.Password, mq.Host, mq.Port, mq.Database)
	global.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println("mysql is error")
		return
	}
	fmt.Println("mysql is success !!!")
}
